import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../config/app_theme.dart';
import '../../models/video.dart';
import '../../utils/app_icons.dart';
import '../../providers/app_state.dart';

class VideoDetailScreen extends StatefulWidget {
  final Video video;

  const VideoDetailScreen({Key? key, required this.video}) : super(key: key);

  @override
  _VideoDetailScreenState createState() => _VideoDetailScreenState();
}

class _VideoDetailScreenState extends State<VideoDetailScreen> {
  bool _isPlaying = false;
  final TextEditingController _commentController = TextEditingController();
  List<Map<String, dynamic>> _comments = [];
  
  @override
  void initState() {
    super.initState();
    _loadComments();
  }
  
  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }
  
  // 模拟加载评论
  void _loadComments() {
    // 生成模拟评论数据
    List<Map<String, dynamic>> comments = [];
    
    for (int i = 0; i < widget.video.comments; i++) {
      comments.add({
        'id': i,
        'username': '用户${i + 1}',
        'avatar': 'https://via.placeholder.com/50',
        'content': '这是一条评论，宠物真可爱！这个视频很有趣，我很喜欢。${i % 2 == 0 ? "希望看到更多类似的内容。" : ""}',
        'time': DateTime.now().subtract(Duration(hours: i * 5)),
        'likes': i * 3,
      });
    }
    
    setState(() {
      _comments = comments;
    });
  }
  
  // 添加评论
  void _addComment() {
    if (_commentController.text.trim().isEmpty) return;
    
    setState(() {
      _comments.insert(0, {
        'id': _comments.length,
        'username': '我',
        'avatar': 'https://via.placeholder.com/50',
        'content': _commentController.text,
        'time': DateTime.now(),
        'likes': 0,
      });
      _commentController.clear();
    });
    
    // 显示成功提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('评论发布成功'),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取应用状态
    final appState = Provider.of<AppState>(context);
    final bool isLiked = appState.likedVideos.contains(widget.video.id);
    final bool isFavorite = appState.favoriteVideos.contains(widget.video.id);
    
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 视频播放区域
            Stack(
              children: [
                // 视频内容（这里用图片代替）
                Container(
                  width: double.infinity,
                  height: 250,
                  color: Colors.black,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        _isPlaying = !_isPlaying;
                      });
                    },
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        Image.network(
                          widget.video.thumbnailUrl,
                          width: double.infinity,
                          height: 250,
                          fit: BoxFit.cover,
                        ),
                        if (!_isPlaying)
                          Container(
                            width: 60,
                            height: 60,
                            decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.5),
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              Icons.play_arrow,
                              color: Colors.white,
                              size: 40,
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
                
                // 顶部操作栏
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    color: Colors.black.withOpacity(0.5),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        IconButton(
                          icon: Icon(Icons.arrow_back_ios, color: Colors.white),
                          onPressed: () => Navigator.pop(context),
                        ),
                        Row(
                          children: [
                            IconButton(
                              icon: Icon(
                                isFavorite ? Icons.favorite : Icons.favorite_border,
                                color: isFavorite ? Colors.red : Colors.white,
                              ),
                              onPressed: () {
                                appState.toggleFavoriteVideo(widget.video.id);
                              },
                            ),
                            IconButton(
                              icon: Icon(Icons.share, color: Colors.white),
                              onPressed: () {
                                // TODO: 实现分享功能
                              },
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            
            // 视频信息和评论
            Expanded(
              child: Container(
                color: Colors.white,
                child: Column(
                  children: [
                    // 视频信息
                    Container(
                      padding: EdgeInsets.all(16.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            widget.video.title,
                            style: AppTheme.titleStyle,
                          ),
                          SizedBox(height: 8.0),
                          Text(
                            widget.video.description,
                            style: AppTheme.bodyStyle,
                          ),
                          SizedBox(height: 16.0),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  CircleAvatar(
                                    radius: 16.0,
                                    backgroundImage: NetworkImage('https://via.placeholder.com/50'),
                                  ),
                                  SizedBox(width: 8.0),
                                  Text(
                                    '发布者ID: ${widget.video.userId}',
                                    style: AppTheme.subtitleStyle,
                                  ),
                                ],
                              ),
                              Text(
                                '${widget.video.views}次观看',
                                style: AppTheme.captionStyle,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    
                    // 分割线
                    Divider(height: 1.0),
                    
                    // 互动区域
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          _buildInteractionButton(
                            icon: isLiked ? Icons.thumb_up : Icons.thumb_up_outlined,
                            label: '${widget.video.likes + (isLiked ? 1 : 0)}',
                            isActive: isLiked,
                            onTap: () {
                              appState.toggleLikeVideo(widget.video.id);
                            },
                          ),
                          _buildInteractionButton(
                            icon: Icons.comment_outlined,
                            label: '${_comments.length}',
                            isActive: false,
                            onTap: () {
                              // 已经在评论区域，无需操作
                            },
                          ),
                          _buildInteractionButton(
                            icon: isFavorite ? Icons.favorite : Icons.favorite_border,
                            label: '收藏',
                            isActive: isFavorite,
                            onTap: () {
                              appState.toggleFavoriteVideo(widget.video.id);
                            },
                          ),
                          _buildInteractionButton(
                            icon: Icons.share_outlined,
                            label: '分享',
                            isActive: false,
                            onTap: () {
                              // TODO: 实现分享功能
                            },
                          ),
                        ],
                      ),
                    ),
                    
                    // 分割线
                    Divider(height: 1.0),
                    
                    // 评论列表
                    Expanded(
                      child: _comments.isEmpty
                          ? Center(child: Text('暂无评论，快来发表第一条评论吧！'))
                          : ListView.builder(
                              padding: EdgeInsets.all(16.0),
                              itemCount: _comments.length,
                              itemBuilder: (context, index) {
                                final comment = _comments[index];
                                return _buildCommentItem(comment);
                              },
                            ),
                    ),
                    
                    // 评论输入框
                    Container(
                      padding: EdgeInsets.all(8.0),
                      color: Colors.white,
                      child: Row(
                        children: [
                          Expanded(
                            child: TextField(
                              controller: _commentController,
                              decoration: InputDecoration(
                                hintText: '添加评论...',
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(20.0),
                                ),
                                contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                              ),
                              maxLines: 1,
                            ),
                          ),
                          SizedBox(width: 8.0),
                          IconButton(
                            icon: Icon(Icons.send, color: AppTheme.primaryColor),
                            onPressed: _addComment,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildInteractionButton({
    required IconData icon,
    required String label,
    required bool isActive,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 8.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              color: isActive ? AppTheme.primaryColor : Colors.grey,
              size: 24.0,
            ),
            SizedBox(height: 4.0),
            Text(
              label,
              style: TextStyle(
                fontSize: 12.0,
                color: isActive ? AppTheme.primaryColor : Colors.grey,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  Widget _buildCommentItem(Map<String, dynamic> comment) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(
            radius: 20.0,
            backgroundImage: NetworkImage(comment['avatar']),
          ),
          SizedBox(width: 12.0),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      comment['username'],
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14.0,
                      ),
                    ),
                    Text(
                      _formatTime(comment['time']),
                      style: AppTheme.captionStyle,
                    ),
                  ],
                ),
                SizedBox(height: 4.0),
                Text(
                  comment['content'],
                  style: AppTheme.bodyStyle,
                ),
                SizedBox(height: 8.0),
                Row(
                  children: [
                    Icon(
                      Icons.thumb_up_outlined,
                      size: 16.0,
                      color: Colors.grey,
                    ),
                    SizedBox(width: 4.0),
                    Text(
                      '${comment['likes']}',
                      style: AppTheme.captionStyle,
                    ),
                    SizedBox(width: 16.0),
                    Text(
                      '回复',
                      style: TextStyle(
                        fontSize: 12.0,
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);
    
    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
} 